package com.bto.solar.work.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.bto.solar.work.common.BizException;
import com.bto.solar.work.constant.BizTaskStateEnum;
import com.bto.solar.work.constant.Constants;
import com.bto.solar.work.constant.DBConstants;
import com.bto.solar.work.constant.LeaseStateEnum;
import com.bto.solar.work.dao.ILeaseReviewService;
import com.bto.solar.work.dao.IOrderBaseService;
import com.bto.solar.work.dto.lease.ContractFileRes;
import com.bto.solar.work.entity.LeaseReview;
import com.bto.solar.work.entity.OrderBase;
import com.bto.solar.work.entity.User;
import com.bto.solar.work.lease.LeaseApi;
import com.bto.solar.work.utils.NullUtils;
import com.bto.solar.work.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class BtoLeaseReviewService {

    @Value("${lease.sign-url}")
    private String signUrl;

    @Autowired
    private ILeaseReviewService leaseReviewService;
    @Autowired
    private LeaseApi leaseApi;
    @Autowired
    private IOrderBaseService orderBaseService;
    @Autowired
    private BtoUserService btoUserService;

    public String getSignUrlByOrderId(String orderId){
        LeaseReview leaseReview = leaseReviewService.lambdaQuery().eq(LeaseReview::getOrderId, orderId).one();
        if (leaseReview == null){
            throw new BizException("没有找到越秀同步进件审核信息");
        }
        return signUrl + leaseReview.getBusinessKey();
//        return signUrl +"2309181725118154";

    }

    /**
    * 判断订单是否起租
    */
    public boolean isOrderIncept(String orderId){
        LeaseReview leaseReview = leaseReviewService.lambdaQuery()
                .eq(LeaseReview::getOrderId, orderId).one();
        if(NullUtils.isNotNull(leaseReview)){
            return BizTaskStateEnum.INCEPT.getStateId().equals(leaseReview.getContractStatus());
        }
        return false;
    }

    /**
     * 越秀合同下载按钮控制
     */
    public Map<String, Boolean> getSignUrlByUseId() {
        Map<String, Boolean> map = new HashMap<>();
        //如果不是总部公司员工只能下载 博通屋顶租赁协议23.04.03.pdf
        User loginUser = btoUserService.getCurrentUser();
        if (!btoUserService.isUserBelongHeadCompany(loginUser)) {
            map.put(DBConstants.TENANT, true);
            map.put(DBConstants.SELLER, false);
            map.put(DBConstants.FACTORY, false);
        } else {
            map.put(DBConstants.TENANT, true);
            map.put(DBConstants.SELLER, true);
            map.put(DBConstants.FACTORY, true);
        }
        return map;
    }

    /**
     * 根据orderId获取越秀合同下载链接
     * 这个方法 如果有多个contract对象时会有问题
     */
    public ContractFileRes.Contract.FileMessage getContractFile(String orderId, String contractType) {
        OrderBase orderBase = orderBaseService.getById(orderId);
        if (null == orderBase) {
            throw new BizException("没有找到订单 {} 信息" ,  orderId);
        }
//        orderBase.setOrderId("2305181133465075");

        ContractFileRes contractFileRes = leaseApi.getContractFile(orderBase);
        if (null != contractFileRes && NullUtils.isNotEmpty(contractFileRes.getContract())) {
            List<ContractFileRes.Contract>  contractList = contractFileRes.getContract();
            for (ContractFileRes.Contract contract : contractList) {
                if (NullUtils.isEmpty(contract.getFileMessage())) {
                    throw new BizException("订单{} 没有合同信息！" , orderId);
                }
                List<ContractFileRes.Contract.FileMessage> fileMessageList = contract.getFileMessage();
                for (ContractFileRes.Contract.FileMessage fileMessage : fileMessageList) {
                    if (fileMessage.getUsageCategory().equals(contractType)) {
                        if(StringUtils.isNotEmpty(fileMessage.getUrl())){
                            return fileMessage;
                        }
                        else {
                            throw new BizException("订单 {} 没有合同 {} 下载链接！" , orderId , contractType);
                        }
                    }
                }
            }
        }
        throw new BizException("订单 {} 获取合同信息失败！" , orderId);
    }

    /**
    *输出文件流 -- 本地测试
    */
    public void getPDF(String orderId, String contractType, HttpServletResponse response) throws IOException {
        ContractFileRes.Contract.FileMessage fileMessage = getContractFile(orderId, contractType);
        File flie = new File(fileMessage.getUrl());
        //读取指定路径下面的文件
        InputStream in = Files.newInputStream(flie.toPath());
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        //创建存放文件内容的数组
        byte[] buff =new byte[1024];
        //所读取的内容使用n来接收
        int n;
        //当没有读取完时,继续读取,循环
        while((n=in.read(buff))!=-1){
            //将字节数组的数据全部写入到输出流中
            outputStream.write(buff,0,n);
        }
        //强制将缓存区的数据进行输出
        outputStream.flush();
        //关流
        outputStream.close();
        in.close();
    }


    //输出文件流 -- 生产
    public byte[] getPdfBytes(String orderId, String contractType) throws IOException {
        InputStream inputStream = getPdfStream(orderId, contractType);
        byte[] pdfBytes = IOUtils.toByteArray(inputStream);
        inputStream.close();

        return pdfBytes;
    }

    public InputStream getPdfStream(String orderId, String contractType) throws IOException {
        ContractFileRes.Contract.FileMessage fileMessage = getContractFile(orderId, contractType);
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(fileMessage.getUrl());
        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        return entity.getContent();
    }

    /**
     * 重新提交审核的时候清楚状态
     */
    public void clearLeaseReviewState(String orderId, String... taskIds) {
        LeaseReview leaseReview = leaseReviewService.lambdaQuery().eq(LeaseReview::getOrderId, orderId).one();
        if (null == leaseReview) {
            throw new BizException("订单号：{}，没有越秀审核记录", orderId);
        }
        LambdaUpdateWrapper<LeaseReview>  updateWrapper  = new LambdaUpdateWrapper<>();
        updateWrapper.eq(LeaseReview::getLeaseReviewId, leaseReview.getLeaseReviewId());
        for (String task : taskIds) {
            if (Constants.AGAIN_SYNCPROJECT.equals(task)) {
                updateWrapper.set(LeaseReview::getProjectStatus, null);
            } else if (Constants.AGAIN_OPERATING_SIGN.equals(task)) {
                updateWrapper.set(LeaseReview::getFarmerSignStatus, null);
            } else if (Constants.AGAIN_OPERATING_SIGN_UPDATE.equals(task)){
                updateWrapper.set(LeaseReview::getFarmerSignStatus, LeaseStateEnum.WAITING.getStateId());
            }
        }
        leaseReviewService.update(updateWrapper);
    }



}
